package com.ruoyi.project.tool.push;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * 极光推送util
 */
@SuppressWarnings({"deprecation", "restriction"})
public class JPushUtil {
    private static final JPushUtil instance = new JPushUtil();
    private static final Logger log = LoggerFactory.getLogger(JPushUtil.class);
    private static final String appKey = "41cc0f4359f56599e5ed4136";
    private static final String masterSecret = "58ec5eb5664a8ec79e3709a7";

    private JPushUtil() {
    }

    public static JPushUtil get() {
        return instance;
    }

    /**
     * 给所有人推送消息
     */
    public void pushAll(String msg) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                ClientConfig clientConfig = ClientConfig.getInstance();
                JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, clientConfig);
                try {
                    PushResult result = jpushClient.sendNotificationAll(msg);
                    if (result != null && result.isResultOK()) {
                        log.info("成功推送给所有人信息！");
                    } else {
                        log.info("失败推送给所有人信息！");
                    }
                } catch (APIConnectionException e) {
                    log.error("Connection error. Should retry later. ", e);
                } catch (APIRequestException e) {
                    log.error("Error response from JPush server. Should review and fix it. ", e);
                    log.info("HTTP Status: " + e.getStatus());
                    log.info("Error Code: " + e.getErrorCode());
                    log.info("Error Message: " + e.getErrorMessage());
                    log.info("Msg ID: " + e.getMsgId());
                }
            }
        }).start();
    }

    /**
     * 按照别名推送消息
     *
     * @param alias 用户别名
     * @param title 消息
     */
    public void pushAlias(String alias, String title, Map<String, String> extra) {
        if (alias != null && !"".equals(alias)) {
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//
//                }
//            }).start();
            pushAndroidAndIosWithAlias(alias, title, extra);
        }
    }

    /**
     * 按照别名推送消息
     *
     * @param alias 用户别名
     * @param msg   消息
     */
    public void pushAlias(String alias, String title, String msg, Map<String, String> extra) {
        if (alias != null && !"".equals(alias)) {
            pushAndroidAndIosWithAlias(alias, title, msg, extra);
        }
    }

    /**
     * 按照注册id推送消息
     *
     * @param registrationId 注册id
     * @param title          消息
     */
    public void pushRegistrationID(String registrationId, String title, Map<String, String> extra) {
        if (registrationId != null && !"".equals(registrationId)) {
            pushAndroidAndIosWithRegistrationID(registrationId, title, extra);
        }
    }

    /**
     * 按照注册id推送消息
     *
     * @param registrationId 注册id
     * @param msg            消息
     */
    public void pushRegistrationID(String registrationId, String title, String msg, Map<String, String> extra) {
        if (registrationId != null && !"".equals(registrationId)) {
            pushAndroidAndIosWithRegistrationID(registrationId, title, msg, extra);
        }
    }

    /**
     * 极光通过别名推送到Android设备和IOS设备1
     *
     * @param alias 别名
     * @param title 消息内容
     * @return 极光推送对象 PushPayload
     */
    private void pushAndroidAndIosWithAlias(String alias, String title, Map<String, String> extra) {
        ClientConfig clientConfig = ClientConfig.getInstance();
        JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, clientConfig);
        PushPayload build = PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.alias(alias.split(",")))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .addExtra("type", "information")
                                .addExtras(extra)
                                .setAlert(title)
                                .build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .addExtra("type", "information")
                                .addExtras(extra)
                                .setAlert(title)
                                .build())
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(false)//true-推送生产环境 false-推送开发环境（测试使用参数）
                        .setTimeToLive(90)//消息在JPush服务器的失效时间（测试使用参数）
                        .build())
                .build();
        try {
            PushResult result = jpushClient.sendPush(build);
            if (result != null && result.isResultOK()) {
                log.info("成功推送别名到ANDROID和IOS设备！");
            } else {
                log.info("失败推送别名到ANDROID和IOS设备！");
            }
        } catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            log.error("Error response from JPush server. Should review and fix it. ", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Code: " + e.getErrorCode());
            log.info("Error Message: " + e.getErrorMessage());
            log.info("Msg ID: " + e.getMsgId());
        }
    }

    /**
     * 极光通过注册id推送到Android设备和IOS设备1
     *
     * @param registrationId 注册id
     * @param title          消息内容
     * @return 极光推送对象 PushPayload
     */
    private void pushAndroidAndIosWithRegistrationID(String registrationId, String title, Map<String, String> extra) {
        ClientConfig clientConfig = ClientConfig.getInstance();
        JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, clientConfig);
        PushPayload build = PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.registrationId(registrationId.split(",")))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .addExtra("type", "information")
                                .addExtras(extra)
                                .setAlert(title)
                                .build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .addExtra("type", "information")
                                .addExtras(extra)
                                .setAlert(title)
                                .build())
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(false)//true-推送生产环境 false-推送开发环境（测试使用参数）
                        .setTimeToLive(90)//消息在JPush服务器的失效时间（测试使用参数）
                        .build())
                .build();
        try {
            PushResult result = jpushClient.sendPush(build);
            if (result != null && result.isResultOK()) {
                log.info("成功推送别名到ANDROID和IOS设备！");
            } else {
                log.info("失败推送别名到ANDROID和IOS设备！");
            }
        } catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            log.error("Error response from JPush server. Should review and fix it. ", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Code: " + e.getErrorCode());
            log.info("Error Message: " + e.getErrorMessage());
            log.info("Msg ID: " + e.getMsgId());
        }
    }

    /**
     * 极光通过别名推送到Android设备和IOS设备1
     *
     * @param alias 别名
     * @param msg   消息内容
     * @return 极光推送对象 PushPayload
     */
    private void pushAndroidAndIosWithAlias(String alias, String title, String msg, Map<String, String> extra) {
        ClientConfig clientConfig = ClientConfig.getInstance();
        JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, clientConfig);
        PushPayload build = PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.alias(alias.split(",")))
                .setMessage(Message.newBuilder()
                        .setTitle(title)
                        .setContentType(msg)
                        .addExtras(extra)
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(false)//true-推送生产环境 false-推送开发环境（测试使用参数）
                        .setTimeToLive(90)//消息在JPush服务器的失效时间（测试使用参数）
                        .build())
                .build();
        try {
            PushResult result = jpushClient.sendPush(build);
            if (result != null && result.isResultOK()) {
                log.info("成功推送别名到ANDROID和IOS设备！");
            } else {
                log.info("失败推送别名到ANDROID和IOS设备！");
            }
        } catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            log.error("Error response from JPush server. Should review and fix it. ", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Code: " + e.getErrorCode());
            log.info("Error Message: " + e.getErrorMessage());
            log.info("Msg ID: " + e.getMsgId());
        }
    }

    /**
     * 极光通过注册id推送到Android设备和IOS设备1
     *
     * @param registrationId 注册id
     * @param msg            消息内容
     * @return 极光推送对象 PushPayload
     */
    private void pushAndroidAndIosWithRegistrationID(String registrationId, String title, String msg, Map<String, String> extra) {
        ClientConfig clientConfig = ClientConfig.getInstance();
        JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, clientConfig);
        PushPayload build = PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.registrationId(registrationId.split(",")))
                .setMessage(Message.newBuilder()
                        .setTitle(title)
                        .setContentType(msg)
                        .addExtras(extra)
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(false)//true-推送生产环境 false-推送开发环境（测试使用参数）
                        .setTimeToLive(90)//消息在JPush服务器的失效时间（测试使用参数）
                        .build())
                .build();
        try {
            PushResult result = jpushClient.sendPush(build);
            if (result != null && result.isResultOK()) {
                log.info("成功推送别名到ANDROID和IOS设备！");
            } else {
                log.info("失败推送别名到ANDROID和IOS设备！");
            }
        } catch (APIConnectionException e) {
            log.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            log.error("Error response from JPush server. Should review and fix it. ", e);
            log.info("HTTP Status: " + e.getStatus());
            log.info("Error Code: " + e.getErrorCode());
            log.info("Error Message: " + e.getErrorMessage());
            log.info("Msg ID: " + e.getMsgId());
        }
    }

}
